package TAIC.util ;
import java.io.* ;
import java.util.* ;
import java.net.* ; 

public class GetImage implements Runnable {
	String imageUrl , filePath  ;
	
	public static void main ( String argu [] ) {
		( new GetImage (
		"http://www.co.hernando.fl.us/county_extension/ap/images/smiley_potato.gif" ,
		"c:\\a.gif" )).run() ;
		//System.out.println ( (long) ( Integer.MAX_VALUE  ) + 
		//new String ( "http://www.co.hernando.fl.us/county_extension/ap/images/smiley_potato.gif" ).hashCode() ) ;
	}
	
	public GetImage ( String url , String path ) {
		imageUrl = url ; 
		filePath = path ; 
	}
	
	public void run () {
		int i ;
		if ( (new File ( filePath) ).exists() ) return ; 
		for ( i = 0 ; i < 3 ; i ++ ) 
			if ( download ( imageUrl , filePath + "t" )) {
				(new File ( filePath + "t" )).renameTo( new File ( filePath )) ;
				return ; 
			}
			else System.out.println ( (i + 1)+ "th time failed: " + imageUrl ) ;
		System.out.println ( "Failed: " + imageUrl ) ;
	}
	
	public boolean download(String address, String localFileName) {
		OutputStream out = null;
		URLConnection conn = null;
		InputStream  in = null;
		boolean done = false ;
		try {
			URL url = new URL(address);
			out = new BufferedOutputStream(new FileOutputStream(localFileName));
			conn = url.openConnection();
			conn.setConnectTimeout( 7500 ) ;
			in = conn.getInputStream();
			conn.setReadTimeout( 10000 ) ; 
			byte[] buffer = new byte[1024];
			int numRead;
			long numWritten = 0;
			while ((numRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, numRead);
				numWritten += numRead;
			}
			//System.out.println(localFileName + "\t" + numWritten);
			done = true; 
		} catch (Exception exception) {
			//exception.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException ioe) {
			}
			return done ; 
		}
	}
}